<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" integrity="sha256-CTSx/A06dm1B063156EVh15m6Y67pAjZZaQc89LLSrU=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.24/fancybox/fancybox.css" integrity="sha256-vQkngPS8jiHHH0I6ABTZroZk8NPZ7b+MUReOFE9UsXQ=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"rjyblog.gitee.io","root":"/","images":"/images","scheme":"Pisces","darkmode":false,"version":"8.18.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":null},"fold":{"enable":false,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="介绍C++类的初始化过程">
<meta property="og:type" content="article">
<meta property="og:title" content="C++ 类的构造与析构">
<meta property="og:url" content="https://rjyblog.gitee.io/posts/17009.html">
<meta property="og:site_name" content="任建勇的博客">
<meta property="og:description" content="介绍C++类的初始化过程">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2018-06-23T16:00:00.000Z">
<meta property="article:modified_time" content="2024-01-13T07:45:30.932Z">
<meta property="article:author" content="Jason">
<meta property="article:tag" content="C++">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://rjyblog.gitee.io/posts/17009.html">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://rjyblog.gitee.io/posts/17009.html","path":"posts/17009.html","title":"C++ 类的构造与析构"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>C++ 类的构造与析构 | 任建勇的博客</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">任建勇的博客</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%B1%BB%E7%9A%84%E6%9E%84%E9%80%A0"><span class="nav-text">类的构造</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E5%88%86%E7%B1%BB"><span class="nav-text">构造函数分类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%B1%BB%E7%9A%84%E5%88%9D%E5%A7%8B%E5%8C%96%E9%A1%BA%E5%BA%8F"><span class="nav-text">类的初始化顺序</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%88%9D%E5%A7%8B%E5%8C%96%E6%88%90%E5%91%98%E5%88%97%E8%A1%A8%EF%BC%88member-initializer-list%EF%BC%89"><span class="nav-text">初始化成员列表（member initializer list）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9E%84%E9%80%A0%E5%92%8C%E6%9E%90%E6%9E%84%E9%A1%BA%E5%BA%8F"><span class="nav-text">构造和析构顺序</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%9E%90%E6%9E%84%E5%87%BD%E6%95%B0%E5%AF%BC%E8%87%B4%E7%9A%84%E8%B5%84%E6%BA%90%E6%B3%84%E6%BC%8F"><span class="nav-text">析构函数导致的资源泄漏</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%88%B6%E7%B1%BB%E8%A2%AB%E5%A4%9A%E6%AC%A1%E6%9E%84%E9%80%A0"><span class="nav-text">父类被多次构造</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%95%B0%E7%BB%84%E4%B8%8E%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0"><span class="nav-text">数组与构造函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%82%E8%80%83%E9%93%BE%E6%8E%A5"><span class="nav-text">参考链接</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Jason"
      src="/images/avatar.png">
  <p class="site-author-name" itemprop="name">Jason</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">66</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">13</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">23</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://rjyblog.gitee.io/posts/17009.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.png">
      <meta itemprop="name" content="Jason">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="任建勇的博客">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="C++ 类的构造与析构 | 任建勇的博客">
      <meta itemprop="description" content="介绍C++类的初始化过程">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          C++ 类的构造与析构
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2018-06-24 00:00:00" itemprop="dateCreated datePublished" datetime="2018-06-24T00:00:00+08:00">2018-06-24</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2024-01-13 15:45:30" itemprop="dateModified" datetime="2024-01-13T15:45:30+08:00">2024-01-13</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/C-C/" itemprop="url" rel="index"><span itemprop="name">C/C++</span></a>
        </span>
    </span>

  
</div>

            <div class="post-description">介绍C++类的初始化过程</div>
        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><h2 id="类的构造"><a href="#类的构造" class="headerlink" title="类的构造"></a>类的构造</h2><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">User</span>(<span class="type">int</span> id, string name, string phone);</span><br></pre></td></tr></table></figure>

<p>可以采用如下格式来进行类实例的创建：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">User user = <span class="built_in">User</span>(<span class="number">1</span>, <span class="string">&quot;Jone&quot;</span>, <span class="string">&quot;123456&quot;</span>);</span><br><span class="line"><span class="function">User <span class="title">user</span><span class="params">(<span class="number">1</span>, <span class="string">&quot;Jone&quot;</span>, <span class="string">&quot;123456&quot;</span>)</span></span>;</span><br><span class="line">User* user = <span class="keyword">new</span> <span class="built_in">User</span>(<span class="number">1</span>, <span class="string">&quot;Jone&quot;</span>, <span class="string">&quot;123456&quot;</span>);</span><br><span class="line"></span><br><span class="line">User user = &#123; <span class="number">1</span>, <span class="string">&quot;Jone&quot;</span>, <span class="string">&quot;123456&quot;</span> &#125;;           <span class="comment">//C++ 11</span></span><br><span class="line">User user&#123; <span class="number">1</span>, <span class="string">&quot;Jone&quot;</span>, <span class="string">&quot;123456&quot;</span> &#125;;              <span class="comment">//C++ 11</span></span><br><span class="line">User* user = <span class="keyword">new</span> User&#123; <span class="number">1</span>, <span class="string">&quot;Jone&quot;</span>, <span class="string">&quot;123456&quot;</span> &#125;;  <span class="comment">//C++ 11</span></span><br></pre></td></tr></table></figure>

<p>如果User类有默认构造函数，则下面方式可以直接构造一个类：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">User user;  <span class="comment">//此处不是变量的声明，而是类实例的创建</span></span><br><span class="line">User* user = <span class="keyword">new</span> User;  <span class="comment">//此处也是使用默认构造函数</span></span><br></pre></td></tr></table></figure>

<p>对于只有一个参数的构造函数，可以采用赋值的方式创建一个类实例：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">A a = <span class="number">10</span>;  <span class="comment">//构造函数为 A(int id);</span></span><br></pre></td></tr></table></figure>

<p>这种形式容易带来问题，可以使用<code>explicit</code>来修饰只有一个参数的构造函数，就能禁用这种类的构造写法。</p>
<h2 id="构造函数分类"><a href="#构造函数分类" class="headerlink" title="构造函数分类"></a>构造函数分类</h2><ul>
<li>明确定义的可以传参的普通构造函数；</li>
<li>默认构造函数，如果没有明确定义构造函数，那么编译器就会生成一个默认的构造函数；</li>
<li>拷贝构造函数，如果没有明确定义拷贝构造函数，编译器会默认生成一个拷贝构造函数，默认的拷贝构造函数是浅拷贝，如果需要实现深拷贝，则需要明确定义一个；</li>
<li>赋值运算符，建议和构造函数一起定义，而不要只定义其中一个【<a target="_blank" rel="noopener external nofollow noreferrer" href="https://learn.microsoft.com/zh-cn/cpp/cpp/copy-constructors-and-copy-assignment-operators-cpp?view=msvc-170">参考</a>】；</li>
</ul>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">A</span> &#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="comment">//明确定义的默认构造函数</span></span><br><span class="line">    <span class="built_in">A</span>() &#123; cout &lt;&lt; <span class="string">&quot;A()&quot;</span> &lt;&lt; endl; &#125;</span><br><span class="line">    <span class="comment">//可以传参的普通构造函数</span></span><br><span class="line">    <span class="built_in">A</span>(string name) : <span class="built_in">mName</span>(name) &#123; cout &lt;&lt; <span class="string">&quot;A(&quot;</span> &lt;&lt; name &lt;&lt; <span class="string">&quot;)&quot;</span> &lt;&lt; endl; &#125;</span><br><span class="line">    <span class="comment">//拷贝构造函数</span></span><br><span class="line">    <span class="built_in">A</span>(<span class="type">const</span> A&amp; other) : <span class="built_in">mName</span>(other.mName) &#123; cout &lt;&lt; <span class="string">&quot;A copy(&quot;</span> + other.mName + <span class="string">&quot;)&quot;</span> &lt;&lt; endl; &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function">string <span class="title">getName</span><span class="params">()</span> </span>&#123; <span class="keyword">return</span> mName; &#125;</span><br><span class="line">    <span class="function"><span class="type">void</span> <span class="title">setName</span><span class="params">(string name)</span> </span>&#123; mName = name; &#125;</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">    string mName;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="function">A <span class="title">a</span><span class="params">(<span class="string">&quot;a1&quot;</span>)</span></span>;</span><br><span class="line">    A a1 = a; <span class="comment">//调用的拷贝构造函数</span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上述代码的输出结构是：</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">A(a1)</span><br><span class="line">A copy(a1)</span><br></pre></td></tr></table></figure>

<p>从输出中可以看出赋值操作符调用了拷贝构造函数；</p>
<h2 id="类的初始化顺序"><a href="#类的初始化顺序" class="headerlink" title="类的初始化顺序"></a>类的初始化顺序</h2><p>根据ISO/IEC 14882:1998(E) 中12.6.2一节的介绍。</p>
<blockquote>
<p>Initialization shall proceed in the following order:</p>
<ul>
<li>First, and only for the constructor of the most derived class as described below, virtual base classes shall be initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base class names in the derived class base-specifier-list.</li>
<li>Then, direct base classes shall be initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).</li>
<li>Then, nonstatic data members shall be initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).</li>
<li>Finally, the body of the constructor is executed.</li>
</ul>
</blockquote>
<p>上面的引用文字我没有完全看懂。但可以大体解释如下：</p>
<ul>
<li>首先，对基类进行初始化；</li>
<li>然后，初始化非静态数据成员。对于在初始化成员列表中的数据成员，编译器会使用列表中的值对数据成员进行初始化；没有出现在初始化成员列表中的数据成员，编译器会按照默认方式进行初始化（如果是类，就是调用类的默认构造函数）；</li>
<li>最后，构造函数体会被执行。</li>
</ul>
<h2 id="初始化成员列表（member-initializer-list）"><a href="#初始化成员列表（member-initializer-list）" class="headerlink" title="初始化成员列表（member initializer list）"></a>初始化成员列表（member initializer list）</h2><p>执行构造函数时，先执行初始化列表的内容，若初始化里面没有数据，则编译器按照系统默认的方式对成员变量赋值，随后再进行构造函数中花括号内部的指令。</p>
<ul>
<li>对于引用型成员变量和const常量型成员变量，则必须通过初始化列表初始化该成员变量。</li>
<li>如果成员类或者基类没有默认构造函数，则必须通过初始化表初始化该成员变量。</li>
<li>成员变量初始化顺序有声明顺序决定，而与初始化列表的顺序无关。</li>
<li>对于参数列表中所列的成员变量，可以不包含所有的成员变量。</li>
</ul>
<p>出于效率方面的考虑：对于有默认构造函数的成员类，编译器会在构建父类之前调用成员类的默认构造函数，如果在构造函数中又对该成员类进行赋值，则该成员类的构造函数调用了两次。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">A</span> &#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="built_in">A</span>() &#123; cout &lt;&lt; <span class="string">&quot;A()&quot;</span> &lt;&lt; endl; &#125;</span><br><span class="line">    <span class="built_in">A</span>(string name) &#123; cout &lt;&lt; <span class="string">&quot;A(&quot;</span> &lt;&lt; name &lt;&lt; <span class="string">&quot;)&quot;</span> &lt;&lt; endl; &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">B</span> &#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="built_in">B</span>(A&amp; a);</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">    A _a;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">B::<span class="built_in">B</span>(A&amp; a) &#123;</span><br><span class="line">    cout &lt;&lt; <span class="string">&quot;B()&quot;</span> &lt;&lt; endl;</span><br><span class="line">    <span class="keyword">this</span>-&gt;_a = a;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="function">A <span class="title">a</span><span class="params">(<span class="string">&quot;a1&quot;</span>)</span></span>;</span><br><span class="line">    <span class="function">B <span class="title">b</span><span class="params">(a)</span></span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上述程序的执行结果是：</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">A(a1)</span><br><span class="line">A()</span><br><span class="line">B()</span><br></pre></td></tr></table></figure>

<p>可以看出A的默认构造函数在B构造函数之前被执行了，这不符合预期，我们期望只有A(a1)，而A()是多余的。如果使用初始化列表的方式，则不存在这个问题，将B的构造函数改成如下形式：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">B::<span class="built_in">B</span>(A&amp; a) : _a(a) &#123;</span><br><span class="line">    cout &lt;&lt; <span class="string">&quot;B()&quot;</span> &lt;&lt; endl;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>修改之后的程序运行结果如下，这样就符合预期了：</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">A(a1)</span><br><span class="line">B()</span><br></pre></td></tr></table></figure>

<h2 id="构造和析构顺序"><a href="#构造和析构顺序" class="headerlink" title="构造和析构顺序"></a>构造和析构顺序</h2><p>C++一个原则是：先构造后析构，在类的继承关系中，父类先构造，子类后构造；而析构时，则是子类先析构，父类后析构。如果在一个含注重，栈中构造了先后构造了A、B两个类（注意不是在堆中），则函数退出时，B先执行析构，然后才是A的析构。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">GrandFather</span> &#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="built_in">GrandFather</span>() &#123; std::cout &lt;&lt; <span class="string">&quot;construct grandfather&quot;</span> &lt;&lt; std::endl; &#125;</span><br><span class="line">    ~<span class="built_in">GrandFather</span>() &#123; std::cout &lt;&lt; <span class="string">&quot;destruct grandfather&quot;</span> &lt;&lt; std::endl; &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Father</span> : <span class="keyword">public</span> GrandFather &#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="built_in">Father</span>() &#123; std::cout &lt;&lt; <span class="string">&quot;construct father&quot;</span> &lt;&lt; std::endl; &#125;</span><br><span class="line">    ~<span class="built_in">Father</span>() &#123; std::cout &lt;&lt; <span class="string">&quot;destruct father&quot;</span> &lt;&lt; std::endl; &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Son</span> : <span class="keyword">public</span> Father &#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="built_in">Son</span>() &#123; std::cout &lt;&lt; <span class="string">&quot;construct son&quot;</span> &lt;&lt; std::endl; &#125;</span><br><span class="line">    ~<span class="built_in">Son</span>() &#123; std::cout &lt;&lt; <span class="string">&quot;destruct son&quot;</span> &lt;&lt; std::endl; &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    Son* f = <span class="keyword">new</span> <span class="built_in">Son</span>();</span><br><span class="line">    <span class="keyword">delete</span> f;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">construct grandfather</span><br><span class="line">construct father</span><br><span class="line">construct son</span><br><span class="line">destruct son</span><br><span class="line">destruct father</span><br><span class="line">destruct grandfather</span><br></pre></td></tr></table></figure>

<p>可以看出来，构造函数的顺序是先父类后子类，而析构则是先子类后父类。</p>
<h3 id="析构函数导致的资源泄漏"><a href="#析构函数导致的资源泄漏" class="headerlink" title="析构函数导致的资源泄漏"></a>析构函数导致的资源泄漏</h3><p>如果main函数改为下面代码：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    Father* f = <span class="keyword">new</span> <span class="built_in">Son</span>();</span><br><span class="line">    <span class="keyword">delete</span> f;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">construct grandfather</span><br><span class="line">construct father</span><br><span class="line">construct son</span><br><span class="line">destruct father</span><br><span class="line">destruct grandfather</span><br></pre></td></tr></table></figure>

<p><code>Son</code>的析构函数没有调用，同样如果改成<code>GrandFather* f = new Son();</code>，<code>Son</code>和<code>Father</code>的析构函数都不会被调用。如果析构函数中需要进行资源释放，那么就会导致资源泄漏问题。要解决此问题，需要通过<code>virtual</code>来修饰析构函数。可以只修饰GrandFather的析构，也可以全部都加上virtual。</p>
<h3 id="父类被多次构造"><a href="#父类被多次构造" class="headerlink" title="父类被多次构造"></a>父类被多次构造</h3><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">GrandFather</span> &#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="built_in">GrandFather</span>() &#123; std::cout &lt;&lt; <span class="string">&quot;construct grandfather&quot;</span> &lt;&lt; std::endl; &#125;</span><br><span class="line">    ~<span class="built_in">GrandFather</span>() &#123; std::cout &lt;&lt; <span class="string">&quot;destruct grandfather&quot;</span> &lt;&lt; std::endl; &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Father1</span>: <span class="keyword">public</span> GrandFather &#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="built_in">Father1</span>() &#123; std::cout &lt;&lt; <span class="string">&quot;construct father1&quot;</span> &lt;&lt; std::endl; &#125;</span><br><span class="line">    ~<span class="built_in">Father1</span>() &#123; std::cout &lt;&lt; <span class="string">&quot;destruct father1&quot;</span> &lt;&lt; std::endl; &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Father2</span>: <span class="keyword">public</span> GrandFather &#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="built_in">Father2</span>() &#123; std::cout &lt;&lt; <span class="string">&quot;construct father2&quot;</span> &lt;&lt; std::endl; &#125;</span><br><span class="line">    ~<span class="built_in">Father2</span>() &#123; std::cout &lt;&lt; <span class="string">&quot;destruct father2&quot;</span> &lt;&lt; std::endl; &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Son</span>: <span class="keyword">public</span> Father1, Father2 &#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="built_in">Son</span>() &#123; std::cout &lt;&lt; <span class="string">&quot;construct son&quot;</span> &lt;&lt; std::endl; &#125;</span><br><span class="line">    ~<span class="built_in">Son</span>() &#123; std::cout &lt;&lt; <span class="string">&quot;destruct son&quot;</span> &lt;&lt; std::endl; &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    Son* f = <span class="keyword">new</span> <span class="built_in">Son</span>();</span><br><span class="line">    <span class="keyword">delete</span> f;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>运行程序的输出结果：</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">construct grandfather</span><br><span class="line">construct father1</span><br><span class="line">construct grandfather</span><br><span class="line">construct father2</span><br><span class="line">construct son</span><br><span class="line">destruct son</span><br><span class="line">destruct father2</span><br><span class="line">destruct grandfather</span><br><span class="line">destruct father1</span><br><span class="line">destruct grandfather</span><br></pre></td></tr></table></figure>

<p>可以看到<code>GrandFather</code>被构建了两次，这明显不符合预期。要解决这个问题需要在继承时添加<code>virtual</code>关键字，如下：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Father1</span>: <span class="keyword">virtual</span> <span class="keyword">public</span> GrandFather &#123;&#125;;</span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Father2</span>: <span class="keyword">virtual</span> <span class="keyword">public</span> GrandFather &#123;&#125;;</span><br></pre></td></tr></table></figure>

<h2 id="数组与构造函数"><a href="#数组与构造函数" class="headerlink" title="数组与构造函数"></a>数组与构造函数</h2><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Stock stocks[<span class="number">4</span>];</span><br></pre></td></tr></table></figure>

<p>这个数据会构造4个Stock类，即，调用了4次Stock的默认构造函数。如果数组的元素类没有默认构造函数可以使用下面形式：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Shop shops[<span class="number">4</span>] = &#123;</span><br><span class="line">    <span class="built_in">Stock</span>(<span class="number">0</span>, <span class="string">&quot;name&quot;</span>),</span><br><span class="line">    <span class="built_in">Stock</span>(<span class="number">1</span>, <span class="string">&quot;name&quot;</span>),</span><br><span class="line">    <span class="built_in">Stock</span>(<span class="number">2</span>, <span class="string">&quot;name&quot;</span>),</span><br><span class="line">    <span class="built_in">Stock</span>(<span class="number">3</span>, <span class="string">&quot;name&quot;</span>)</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h2 id="参考链接"><a href="#参考链接" class="headerlink" title="参考链接"></a>参考链接</h2><ul>
<li><a target="_blank" rel="noopener external nofollow noreferrer" href="http://en.cppreference.com/w/cpp/language/initializer_list">Constructors and member initializer lists</a></li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/C/" rel="tag"># C++</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/posts/55021.html" rel="prev" title="C/C++ 程序内存分段">
                  <i class="fa fa-angle-left"></i> C/C++ 程序内存分段
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/posts/63718.html" rel="next" title="C++成员函数指针">
                  C++成员函数指针 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 
    <span itemprop="copyrightYear">2024</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">Jason</span>
  </div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener external nofollow noreferrer" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/pisces/" rel="noopener external nofollow noreferrer" target="_blank">NexT.Pisces</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/next-theme-pjax/0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.24/fancybox/fancybox.umd.js" integrity="sha256-oyhjPiYRWGXaAt+ny/mTMWOnN1GBoZDUQnzzgC7FRI4=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>


  <script class="next-config" data-name="mermaid" type="application/json">{"enable":true,"theme":{"light":"default","dark":"dark"},"js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mermaid/10.5.0/mermaid.min.js","integrity":"sha256-K7oJiQlDulzl24ZUFOywuYme1JqBBvQzK6m8qHjt9Gk="}}</script>
  <script type="module" src="/js/zenuml-definition-074a43fa.js"></script>
  <script type="module" src="/js/mermaid-zenuml.esm.min.mjs"></script>
  <script src="/js/third-party/tags/mermaid.js"></script>


  <script src="/js/third-party/fancybox.js"></script>



  




  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>



</body>
</html>
